
var coreData = require('../resolvers/CoreData');
var response = require('../net/HttpResponse');

var Api2Controller = function () {
};

Api2Controller.prototype.getGlobal = function (req, res) {
  var val = coreData.globalStat().global().meta();
  response(res).ok().send({
    visited: val.visited,
    playCount: val.playCount,
    durations: val.durations,
    users: val.users
  })
};

Api2Controller.prototype.getAppGlobal = function (req, res) {
  var val = coreData.globalStat().app(req.params.appToken).meta();
  response(res).ok().send({
    visited: val.visited,
    playCount: val.playCount,
    durations: val.durations,
    users: val.users
  });
};

Api2Controller.prototype.getCategoryGlobal = function (req, res) {
  var val = coreData.globalStat().category(req.params.category, req.params.appToken).meta();
  response(res).ok().send({
    visited: val.visited,
    playCount: val.playCount,
    durations: val.durations,
    users: val.users
  });
};

Api2Controller.prototype.getContentGlobal = function (req, res) {
  var val = coreData.globalStat().content(req.params.content, req.params.appToken).meta();
  response(res).ok().send({
    visited: val.visited,
    playCount: val.playCount,
    durations: val.durations,
    users: val.users
  });
};

Api2Controller.prototype.getNearest = function (req, res) {
  var query = req.query;
  var count = 0;
  var start = undefined;
  var end = undefined;
  if (query['count']) {
    count = parseInt(query['count']);
  }
  if (query['start']) {
    start = query['start'];
  }
  if (query['end']) {
    end = query['end'];
  }
  var nearest = undefined;
  if (start) {
    nearest = coreData.nearest(start, count);
  }
  if (start && end && !count) {
    nearest = coreData.nearest([start, end]);
  }
  if (nearest === undefined) {
    nearest = coreData.nearest(count);
  }
  
};

Api2Controller.prototype.onRouting = function (router) {
  router.get('/global', this.getGlobal);
  router.get('/global/:appToken', this.getAppGlobal);
  router.get('/global/:appToken/:category', this.getCategoryGlobal);
  router.get('/global/:appToken/:category/:content', this.getContentGlobal);

  router.get('/flavor');
  router.get('/flavor/:appToken');
  router.get('/flavor/:appToken/:category');
  router.get('/flavor/:appToken/:category/:content');

  router.get('/time');
  router.get('/time/:appToken');
  router.get('/time/:appToken/:category');
  router.get('/time/:appToken/:category/:content');

  router.get('/app/global');
};

module.exports = Api2Controller;